# _*_ coding:utf-8 _*_

from django.http import Http404
from django.shortcuts import get_object_or_404
from collections import OrderedDict
from Persimmon.celery import app
from celery.utils.log import get_task_logger


# def insert_comment_node(comment_tree, comment_obj):
# 	for pre_comment, _ in comment_tree.items():
# 		if comment_obj.parent_comment == pre_comment:
# 			comment_tree[pre_comment][comment_obj]={}
# 		else:
# 			insert_comment_node(comment_tree[pre_comment],comment_obj)

def build_comment_tree(movie_obj):
	all_comments = movie_obj.comment_set.select_related().order_by('-timestamp')
	comment_tree = OrderedDict()
	for comment in all_comments:
		comment_tree[comment] = {}
	return comment_tree


logger = get_task_logger(__name__)


# @periodic_task(
# 	run_every=(crontab(minute='*/15')),
# 	name="calculate_movie_latest_score",
# 	ignore_result=True,
# )
@app.task
def calculate_movie_latest_score():
	from movie.models import Movie, Stamp
	from auser.models import User
	movies = Movie.objects.all()
	for movie in movies:
		value = 0
		# rate_peo = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
		for ua in User.objects.all():
			try:
				stamp = get_object_or_404(Stamp, movie=movie, user=ua)
			except Http404:
				continue
			else:
				value += stamp.rate
		main_calcute(value, movie)


# TODO:大数据处理
# def do_calcute(rate_peo, movie):
# 	proportion = [map(lambda peo: peo / movie.stamps.count(), rate_peo)]
# 	total = 0
# 	for i in range(11):
# 		total += proportion[i] * i
# 	return total


def main_calcute(value, movie):
	peo = movie.stamps.count() + 1
	logger.info(value)
	result = (movie.rating + value) / peo
	movie.rating = float('%.2f' % result)
	movie.save(update_fields=['rating'])
